package com.ruoci.redis.specialcontroller;

import cn.hutool.core.date.DateUtil;
import com.ruoci.redis.constants.BusinessConstants;
import com.ruoci.redis.response.BasicResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author yanglingjun
 * 统计网页不同账户访问量UV(Unique Visitor)
 * 统计网站日活用户
 */
@Slf4j
@RestController
@RequestMapping("/hll")
public class HyperloglogController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     *
     * 统计网站日活用户
     * @return
     */
    @GetMapping("/add")
    public BasicResponse add(){
        String userId1 = "10005";
        String userId2 = "10006";
        String keySuffix = BusinessConstants.ACTIVE_USER_KEY.concat(DateUtil.format(new Date(), BusinessConstants.HLL_DATA_FORMAT));
        HyperLogLogOperations operations = redisTemplate.opsForHyperLogLog();
        operations.add(keySuffix,userId1,userId2);
        return BasicResponse.success();
    }

    /**
     *
     * 获取日活用户总数
     * @return
     */
    @GetMapping("/get")
    public BasicResponse get(){
        String keySuffix = BusinessConstants.ACTIVE_USER_KEY.concat(DateUtil.format(new Date(), BusinessConstants.HLL_DATA_FORMAT));
        HyperLogLogOperations operations = redisTemplate.opsForHyperLogLog();
        Long size = operations.size(keySuffix);
        return BasicResponse.success(size);
    }

    /**
     * 统计多个日活跃用户总数
     */
    @GetMapping("/count")
    public BasicResponse count(){
        String keySuffix = BusinessConstants.ACTIVE_USER_KEY.concat(DateUtil.format(new Date(), BusinessConstants.HLL_DATA_FORMAT));
        HyperLogLogOperations operations = redisTemplate.opsForHyperLogLog();
        Long union = operations.union(keySuffix);
        return BasicResponse.success(union);
    }


}
